package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import net.miginfocom.swing.MigLayout;
import dto.LogonDTO;
import dto.UserDTO;

public class SearchUserPage extends JDialog {

	private static final long serialVersionUID = 1L;

	private JPanel panel;
	// int foundCount = 0;
	private JLabel labelMessage;
	private JPanel panelResults;

	private JTextField textFieldUsername;
	private JTextField textFieldEditorUsername;
	private JTextField textFieldEditorLevel;

	private LogonDTO logonDTO;
	private UserDTO userDTO;
	private List<UserDTO> searchedUsers;
	private JLabel lblUsernamename;

	JButton btnSearchButton = new JButton("Search User");

	public LogonDTO getLogonDTO() {
		return logonDTO;
	}

	public UserDTO getUserDTO() {
		userDTO.setUserId(textFieldUsername.getText().trim());
		return userDTO;
	}

	public List<UserDTO> getSearchedUsers() {
		return searchedUsers;
	}

	public void setSearchedUsers(List<UserDTO> searchedUsers) {
		this.searchedUsers = searchedUsers;
	}

	/**
	 * Create the dialog.
	 */
	public SearchUserPage(LogonDTO logonDTO) {

		this.logonDTO = logonDTO;
		this.userDTO = new UserDTO();

		setBounds(100, 100, 450, 452);
		{
			panel = new JPanel();
			getContentPane().add(panel, BorderLayout.NORTH);
			panel.setLayout(new MigLayout("",
					"[grow][74.00,grow][65.00][136.00][61.00][grow]",
					"[][][][][][][][]"));
			{
				JLabel lblJaLibrary = new JLabel("J&A Library");
				lblJaLibrary.setFont(new Font("Arial", Font.BOLD, 16));
				lblJaLibrary.setForeground(Color.BLUE);
				panel.add(lblJaLibrary, "cell 0 0 6 1,alignx center");
			}
			{
				JLabel lblEditdeleteUser = new JLabel("Edit/Delete User");
				panel.add(lblEditdeleteUser, "cell 0 1 6 1,alignx center");
			}
			{
				JLabel label = new JLabel("     ");
				panel.add(label, "cell 0 2");
			}
			{
				lblUsernamename = new JLabel("Username/Name:");
				panel.add(lblUsernamename, "cell 0 3,alignx center");
			}
			{
				textFieldUsername = new JTextField();
				panel.add(textFieldUsername, "cell 1 3 4 1,growx");
				textFieldUsername.setColumns(10);
			}

			// SEARCH button
			panel.add(btnSearchButton, "cell 0 5");

			JButton btnReturnToMain = new JButton("Return to Main Menu");
			btnReturnToMain.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					dispose();
				}
			});

			// RETURN TO MAIN button
			panel.add(btnReturnToMain, "cell 5 5,alignx left");

			{
				textFieldEditorUsername = new JTextField();
				textFieldEditorUsername.setEditable(false);
				textFieldEditorUsername.setText(logonDTO.getUserName());
				panel.add(textFieldEditorUsername, "cell 0 6 3 1,growx");
				textFieldEditorUsername.setColumns(10);
			}
			{
				textFieldEditorLevel = new JTextField();
				textFieldEditorLevel
						.setHorizontalAlignment(SwingConstants.RIGHT);
				textFieldEditorLevel.setEditable(false);
				textFieldEditorLevel.setText(logonDTO.getUserTitle());
				panel.add(textFieldEditorLevel, "cell 4 6 2 1,growx");
				textFieldEditorLevel.setColumns(10);
			}
			{
				labelMessage = new JLabel("     ");
				labelMessage.setForeground(Color.BLUE);
				panel.add(labelMessage, "cell 0 7 6 1");
			}
		}
		{
			JScrollPane scrollPane = new JScrollPane();
			getContentPane().add(scrollPane, BorderLayout.CENTER);
			{
				panelResults = new JPanel();
				scrollPane.setViewportView(panelResults);
				drawBottomPanelHeader(panelResults);
			}
		}
	}

	private void drawBottomPanelHeader(JPanel panel) {
		if (panel.getComponentCount() > 0) {
			panel.removeAll();
		}
		panel.setLayout(new MigLayout("", "[][grow][][][][]",
				"[][][][][][][][][][][][]"));
	}

	// private int searchDatabase(JPanel panel) {
	// drawBottomPanelHeader(panel);
	// foundCount = 0;
	// String criteriaUsername = textFieldUsername.getText();
	// String criteriaName = textFieldName.getText();
	// if (criteriaUsername.length() == 0)
	// criteriaUsername = "";
	// if (criteriaName.length() == 0)
	// criteriaName = "";
	//
	// if ((chckbxUsername.isSelected()) && (chckbxName.isSelected())) {
	// System.out.println(criteriaUsername);
	// System.out.println(criteriaName);
	// databaseOut(1);
	// return reDrawThis(panel);
	// }
	// if (chckbxUsername.isSelected()) {
	// System.out.println(criteriaUsername);
	// databaseOut(2);
	// return reDrawThis(panel);
	// }
	// if (chckbxName.isSelected()) {
	// System.out.println(criteriaName);
	// databaseOut(3);
	// return reDrawThis(panel);
	// }
	// return -1;
	// }

	public void reDrawThis(ActionListener editUserListener,
			ActionListener deleteUserListener) {

		panelResults.removeAll();
		int selectedBookIndex = 1;

		for (UserDTO searchedUser : searchedUsers) {
			String id = searchedUser.getUserId();
			String username = searchedUser.getUserName();

			JLabel label = new JLabel(selectedBookIndex + ".");
			panelResults.add(label, "flowx,cell 0 " + selectedBookIndex);

			JButton btnEditUser = new JButton("[" + id + "] " + username);
			btnEditUser.setActionCommand(String.valueOf(selectedBookIndex - 1));
			if ((id.equalsIgnoreCase("admin"))
					|| (id.equalsIgnoreCase("guest"))) {
				btnEditUser.setEnabled(false);
			}
			btnEditUser.addActionListener(editUserListener);
			btnEditUser.setFont(new Font("Arial", Font.PLAIN, 11));
			panelResults.add(btnEditUser, "cell 1 " + selectedBookIndex
					+ " 4 1,growx");

			JButton btnDelete = new JButton("Delete");
			btnDelete.setActionCommand(String.valueOf(selectedBookIndex - 1));
			if ((id.equalsIgnoreCase("admin"))
					|| (id.equalsIgnoreCase("guest"))) {
				btnDelete.setEnabled(false);
			}
			btnDelete.addActionListener(deleteUserListener);
			panelResults.add(btnDelete, "cell 5 " + selectedBookIndex
					+ ",alignx right");

			panelResults.revalidate();
			panelResults.repaint();

			selectedBookIndex++;
		}
	}

	// private void addToFoundList(String userName, String name) {
	// if (userName.length() == 0)
	// userName = "";
	// if (name.length() == 0)
	// name = "";
	// foundCount++;
	// {
	// JLabel label = new JLabel(foundCount + ".");
	// panelResults.add(label, "flowx,cell 0 " + foundCount);
	// }
	// {
	// JButton btnusernameName = new JButton("[" + userName + "] " + name);
	// btnusernameName.setActionCommand(userName);
	// if ((userName.toLowerCase().trim().equals("admin"))
	// || (userName.toLowerCase().trim().equals("guest"))) {
	// btnusernameName.setEnabled(false);
	// } else {
	// btnusernameName.setEnabled(true);
	// }
	// btnusernameName.addActionListener(new ActionListener() {
	// public void actionPerformed(ActionEvent arg0) {
	// // TODO Edit Page
	// // EditUser editUserPage = new EditUser(editorUsername,
	// // editorLevel, arg0.getActionCommand());
	// // editUserPage.execute();
	// // searchDatabase(panelResults);
	// }
	// });
	// btnusernameName.setFont(new Font("Arial", Font.PLAIN, 11));
	// panelResults.add(btnusernameName, "cell 1 " + foundCount
	// + " 4 1,growx");
	// }
	// {
	// JButton btnDelete = new JButton("Delete");
	// btnDelete.setActionCommand(userName);
	// if ((userName.toLowerCase().trim().equals("admin"))
	// || (userName.toLowerCase().trim().equals("guest"))) {
	// btnDelete.setEnabled(false);
	// } else {
	// btnDelete.setEnabled(true);
	// }
	// btnDelete.addActionListener(new ActionListener() {
	// public void actionPerformed(ActionEvent arg0) {
	// // delete this
	// AreYouSurePage confirm = new AreYouSurePage(
	// "Are you sure you want to delete this User?", arg0
	// .getActionCommand());
	// if (confirm.execute()) {
	// System.out.println("deleting.");
	// deleteThis(arg0.getActionCommand());
	// searchDatabase(panelResults);
	// }
	// }
	// });
	// panelResults.add(btnDelete, "cell 5 " + foundCount
	// + ",alignx right");
	// }
	// }
	//
	// private int reDrawThis(JPanel panel) {
	// panel.revalidate();
	// panel.repaint();
	// return foundCount;
	// }

	// private void databaseOut(int criteria) {
	// String criteriaUsername = textFieldUsername.getText();
	// String criteriaName = textFieldName.getText();
	// Connection con = null;
	// try {
	// System.out.println("connecting...");
	// Class.forName("com.mysql.jdbc.Driver");
	// con = DriverManager.getConnection(
	// "jdbc:mysql://localhost:3306/librarydb", "root", ""); // null
	// // password
	// if (!con.isClosed())
	// System.out.println("Sucessfully connected.");
	// else
	// System.out.println("");
	//
	// Statement statement = con.createStatement();
	// ResultSet result = null;
	// switch (criteria) {
	// case 1:// username and userid
	// result = statement
	// .executeQuery("SELECT userid,username from user where userid like '%"
	// + criteriaUsername
	// + "%' AND username LIKE '%"
	// + criteriaName + "%'");
	// break;
	// case 2: // userid
	// result = statement
	// .executeQuery("SELECT userid,username from user where userid like '%"
	// + criteriaUsername + "%'");
	// break;
	// case 3: // username
	// result = statement
	// .executeQuery("SELECT userid,username from user where username like '%"
	// + criteriaName + "%'");
	// break;
	// }
	//
	// if (result != null)
	// while (result.next()) {
	// addToFoundList(result.getString(1), result.getString(2));
	// }
	//
	// } catch (Exception e) {
	// System.err.println("Exception: " + e.getMessage());
	//
	// } finally {
	// try {
	// con.close();
	// } catch (SQLException e) {
	// }
	// }
	//
	// }

	// private void sampleDatabaseOut() {
	// addToFoundList("acortes", "Allan Cortes");
	// addToFoundList("jfaiwas", "Jen Faiwas");
	// addToFoundList("acortes", "Allan Cortes");
	// addToFoundList("jfaiwas", "Jen Faiwas");
	// addToFoundList("acortes", "Allan Cortes");
	// addToFoundList("jfaiwas", "Jen Faiwas");
	// addToFoundList("acortes", "Allan Cortes");
	// addToFoundList("jfaiwas", "Jen Faiwas");
	// addToFoundList("acortes", "Allan Cortes");
	// addToFoundList("jfaiwas", "Jen Faiwas");
	// }

	// private boolean deleteThis(String username) {
	// Connection con = null;
	// try {
	// System.out.println("connecting...");
	// Class.forName("com.mysql.jdbc.Driver");
	// con = DriverManager.getConnection(
	// "jdbc:mysql://localhost:3306/librarydb", "root", ""); // null
	// // password
	// if (!con.isClosed())
	// System.out.println("Sucessfully connected.");
	// else
	// System.out.println("");
	//
	// Statement statement = con.createStatement();
	// System.out.println("delete existing");
	// statement.executeUpdate("delete from user where userid='"
	// + username + "'");
	// } catch (Exception e) {
	// System.err.println("Exception: " + e.getMessage());
	// } finally {
	// try {
	// con.close();
	// } catch (SQLException e) {
	// }
	// }
	// return true;
	// }

	public void addSearchUserButtonListener(ActionListener al) {
		btnSearchButton.addActionListener(al);
	}

	public int showConfirmDialog(String userStr) {

		return JOptionPane.showConfirmDialog(panel,
				"Are you sure you want to delete this user?\n" + userStr,
				"Confirm Delete", JOptionPane.YES_NO_OPTION);
	}

	public void displayMessage(String message) {
		labelMessage.setText(message);
	}

}
